<?php

namespace apiend\models;

use Yii;
use common\base\Model;
use apiend\models\User;

/**
 * 帐号密码登录
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class LoginForm extends Model {

    public $username;
    public $password;
    public $token = null;
    //
    private $_user = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params) {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, '用户名或者密码错误');
            }
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return \api\models\UserCompatibleModel|null
     */
    protected function getUser() {
        if ($this->_user === null) {
            $this->_user = User::findByAccount($this->username);
        }
        return $this->_user;
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return bool whether the user is logged in successfully
     */
    public function login() {
        if (!$this->validate()) {
            $this->dumpError('输入的帐号或密码错误');
        }
        return $this->getUser()->meta;
    }

}
